package com.itcoon.cloud.framework.mybatis.typehandler;/**
 * @author Athric Yu
 * 2024/11/29
 **/

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/29
 **/
public abstract class AbstractToStringTypeHandler<T> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, convertNonNull(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String column = rs.getString(columnName);
        return StringUtils.isBlank(column) ? null : reverseNonNullConvert(column);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String column = rs.getString(columnIndex);
        return StringUtils.isBlank(column) ? null : reverseNonNullConvert(column);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String column = cs.getString(columnIndex);
        return StringUtils.isBlank(column) ? null : reverseNonNullConvert(column);
    }

    abstract String convertNonNull(T t);

    abstract T reverseNonNullConvert(String column);
}
